<template>
  <div class="examine-engie-basic">
    <h2>审批节点管理</h2>

    <div class="toolbar">
      <input v-model.trim="search.keyword" placeholder="按名称/编号搜索" @keyup.enter="onSearch" />
      <button @click="onSearch">查询</button>
      <button class="plain" @click="onReset">重置</button>
      <button @click="onAddClick">新增节点</button>
    </div>

    <table class="node-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>编号</th>
          <th>名称</th>
          <th>审批人</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in nodes" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.nodeCode }}</td>
          <td>{{ item.nodeName }}</td>
          <td>{{ item.approverNicknames || item.approverName || '-' }}</td>
          <td>
            <button @click="onEditClick(item)">编辑</button>
            <button class="danger" @click="onDeleteClick(item)">删除</button>
          </td>
        </tr>
        <tr v-if="!loading && nodes.length === 0">
          <td colspan="5" style="text-align:center;color:#909399;">暂无数据</td>
        </tr>
      </tbody>
    </table>

    <div class="pagination">
      <div class="page-size">
        <span>每页</span>
        <div class="page-size-group">
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 10 }" @click="setPageSize(10)">10</button>
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 20 }" @click="setPageSize(20)">20</button>
          <button type="button" class="page-size-pill" :class="{ active: pageSize === 50 }" @click="setPageSize(50)">50</button>
        </div>
      </div>
      <div class="pager-controls">
        <button :disabled="currentPage===1" @click="goPrev">上一页</button>
        <span>第 {{ currentPage }} / {{ totalPage }} 页</span>
        <button :disabled="currentPage>=totalPage" @click="goNext">下一页</button>
      </div>
    </div>

    

    <div v-if="dialog.visible" class="dialog-mask">
      <div class="dialog">
        <h3>{{ dialog.mode === 'create' ? '新增节点' : '编辑节点' }}</h3>
        <div class="form-row">
          <label>节点名称</label>
          <input v-model="form.nodeName" placeholder="请输入节点名称" />
        </div>
        <div class="form-row">
          <label>节点编号</label>
          <input :value="'自动生成'" disabled />
        </div>
        <div class="form-row">
          <label>审批人</label>
          <div class="multi-select-container">
            <div 
              class="multi-select-dropdown" 
              @click="toggleUserDropdown"
              :class="{ 'active': userDropdownVisible }"
            >
              <span v-if="selectedUsers.length === 0" class="placeholder">请选择审批人</span>
              <span v-else>{{ selectedUsers.map(u => u.nickname || u.account).join(', ') }}</span>
              <span class="arrow">▼</span>
            </div>
            <div v-if="userDropdownVisible" class="dropdown-menu">
              <div 
                v-for="user in users" 
                :key="user.id"
                class="dropdown-item"
                @click="toggleUserSelection(user)"
              >
                <input 
                  type="checkbox" 
                  :checked="selectedUsers.some(u => u.id === user.id)"
                  @change="toggleUserSelection(user)"
                />
                <span>{{ user.nickname || user.account }} ({{ user.account }})</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="dialog-actions">
          <button @click="onSubmit">确定</button>
          <button class="plain" @click="onCancel">取消</button>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import { examineApi } from '@/api'

type NodeItem = {
  id: number
  nodeCode: string
  nodeName: string
  approverCode: string
  approverNicknames?: string
  approverName?: string
}

type UserItem = {
  id: number
  nickname?: string
  account?: string
  phone?: string
  email?: string
}

const nodes = ref<NodeItem[]>([])
const users = ref<UserItem[]>([])
const selectedUsers = ref<UserItem[]>([])
const userDropdownVisible = ref(false)
const loading = ref(false)
const error = ref('')
const currentPage = ref(1)
const totalPage = ref(1)
const pageSize = ref(10)
const search = reactive({ keyword: '' })

const dialog = reactive({
  visible: false,
  mode: 'create' as 'create' | 'edit',
})

const form = reactive<NodeItem>({
  id: 0,
  nodeCode: '',
  nodeName: '',
  approverCode: ''
})

function resetForm() {
  form.id = 0
  form.nodeName = ''
  form.nodeCode = ''
  form.approverCode = ''
  selectedUsers.value = []
  userDropdownVisible.value = false
}

async function loadNodes() {
  try {
    loading.value = true
    error.value = ''
    const res = await examineApi.getNodes({ 
      pageindex: currentPage.value, 
      pageSize: pageSize.value,
      keyword: search.keyword || undefined
    })
    console.log('节点列表API响应:', res)
    const container: any = (res && (res as any).data) ? (res as any).data : res
    const list = (Array.isArray(container?.data) ? container.data : (Array.isArray(container?.Data) ? container.Data : [])) as any[]
    console.log('原始数据列表:', list)
    nodes.value = list.map((x, i) => ({
      id: x.nodeId ?? x.NodeId ?? i + 1,
      nodeCode: x.nodeCode ?? x.NodeCode ?? '',
      nodeName: x.nodeName ?? x.NodeName ?? '',
      approverCode: x.approverCode ?? x.ApproverCode ?? '',
      approverNicknames: x.approverNicknames ?? x.ApproverNicknames ?? '',
      approverName: x.approverName ?? x.ApproverName ?? '',
    }))
    const totalCount = container?.TotalCount ?? container?.totalCount ?? nodes.value.length
    totalPage.value = container?.TotalPage ?? container?.totalPage ?? Math.max(1, Math.ceil((Number(totalCount)||0)/pageSize.value))
  } catch (e) {
    console.error('加载节点失败', e)
    error.value = '加载失败'
  } finally {
    loading.value = false
  }
}

async function loadUsers() {
  try {
    const res = await examineApi.getUsers({ pageindex: 1, pageSize: 100 })
    const list = (res.data?.data || []) as any[]
    users.value = list.map((x: any) => ({
      id: x.id ?? x.Id ?? 0,
      nickname: x.nickname ?? x.Nickname ?? '',
      account: x.account ?? x.Account ?? '',
      phone: x.phone ?? x.Phone ?? '',
      email: x.email ?? x.Email ?? '',
    }))
  } catch (e) {
    console.error('加载用户失败', e)
  }
}

function onAddClick() {
  resetForm()
  dialog.mode = 'create'
  dialog.visible = true
}

function onEditClick(item: NodeItem) {
  form.id = item.id
  form.nodeName = item.nodeName || ''
  form.nodeCode = item.nodeCode || ''
  form.approverCode = item.approverCode || ''
  
  selectedUsers.value = []
  if (item.approverCode) {
    const approverCodes = item.approverCode.split(',').map(code => code.trim())
    selectedUsers.value = users.value.filter(user => 
      approverCodes.includes(user.id?.toString() || '')
    )
  }
  
  dialog.mode = 'edit'
  dialog.visible = true
}

async function onDeleteClick(item: NodeItem) {
  try {
    await examineApi.deleteNode({ NodeId: item.id })
    nodes.value = nodes.value.filter(x => x.id !== item.id)
    console.log('删除成功')
  } catch (e) {
    console.error('删除失败', e)
  }
}

async function onSubmit() {
  try {
    const approverCodes = selectedUsers.value.map(user => user.id || '').join(',')
    
    if (dialog.mode === 'create') {
      const payload: any = {
        NodeName: form.nodeName || '普通节点',
        ApproverCode: approverCodes || '1'
      }
      await examineApi.createNode(payload)
      await loadNodes()
    } else {
      const payload: any = {
        NodeId: form.id,
        NodeName: form.nodeName || '普通节点',
        ApproverCode: approverCodes || '1'
      }
      await examineApi.updateNode(payload)
      await loadNodes()
    }
    dialog.visible = false
  } catch (e) {
    console.error('保存失败', e)
  }
}

function onCancel() {
  dialog.visible = false
}

function toggleUserDropdown() {
  userDropdownVisible.value = !userDropdownVisible.value
}

function toggleUserSelection(user: UserItem) {
  const index = selectedUsers.value.findIndex(u => u.id === user.id)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
  } else {
    selectedUsers.value.push(user)
  }
}

function handleClickOutside(event: Event) {
  const target = event.target as HTMLElement
  if (!target.closest('.multi-select-container')) {
    userDropdownVisible.value = false
  }
}

onMounted(() => {
  loadNodes()
  loadUsers()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

function onSearch() {
  currentPage.value = 1
  loadNodes()
}

function onReset() {
  search.keyword = ''
  currentPage.value = 1
  loadNodes()
}

function onPageSizeChange() {
  currentPage.value = 1
  loadNodes()
}

function goPrev() {
  if (currentPage.value > 1) { currentPage.value -= 1; loadNodes() }
}

function goNext() {
  if (currentPage.value < totalPage.value) { currentPage.value += 1; loadNodes() }
}

function setPageSize(size: number) {
  if (pageSize.value === size) return
  pageSize.value = size
  onPageSizeChange()
}
</script>

<style scoped>
.examine-engie-basic {
  padding: 16px;
}

.toolbar {
  margin-bottom: 12px;
}

button {
  padding: 6px 12px;
  margin-right: 8px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  background: #fff;
  border-radius: 4px;
}

button.danger {
  background: #ff4d4f;
  color: #fff;
  border: none;
}

button.plain {
  background: transparent;
  border: 1px solid #ccc;
}

.node-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
}

.node-table th,
.node-table td {
  border: 1px solid #eaeaea;
  padding: 8px;
  text-align: left;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.pagination .page-size { display:flex; align-items:center; gap:8px; }
.page-size-group { display:inline-flex; background:#f0f2f5; border:1px solid #d9d9d9; border-radius:999px; padding:2px; }
.page-size-pill { border:none; background:transparent; padding:6px 12px; border-radius:999px; cursor:pointer; font-size:12px; color:#606266; }
.page-size-pill.active { background:#fff; color:#303133; border:1px solid #d9d9d9; }
.pager-controls { display:flex; align-items:center; gap:10px; }

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.dialog-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.45);
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog {
  width: 440px;
  background: #fff;
  border-radius: 6px;
  padding: 16px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.form-row label {
  width: 72px;
  color: #666;
}

.form-row input[type="text"],
.form-row input[type="number"] {
  flex: 1;
  padding: 6px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.dialog-actions {
  text-align: right;
}

/* 多选下拉框样式 */
.multi-select-container {
  position: relative;
  flex: 1;
}

.multi-select-dropdown {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  background: #fff;
  min-height: 32px;
}

.multi-select-dropdown:hover {
  border-color: #c0c4cc;
}

.multi-select-dropdown.active {
  border-color: #409eff;
}

.placeholder {
  color: #c0c4cc;
}

.arrow {
  color: #c0c4cc;
  transition: transform 0.3s;
}

.multi-select-dropdown.active .arrow {
  transform: rotate(180deg);
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-top: none;
  border-radius: 0 0 4px 4px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
}

.dropdown-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f5f7fa;
}

.dropdown-item:hover {
  background: #f5f7fa;
}

.dropdown-item:last-child {
  border-bottom: none;
}

.dropdown-item input[type="checkbox"] {
  margin-right: 8px;
}

.dropdown-item span {
  flex: 1;
  font-size: 14px;
}
</style>



